-- UIBuyGoods
-- Created by chengb Feb/4/2015
-- 商品购买界面

UIBuyGoods = class("UIBuyGoods", function()
    return cc.Layer:create();
end);

function UIBuyGoods.create(goodsId, priceType)
    return UIBuyGoods.new(goodsId, priceType);
end

-- 构造函数
function UIBuyGoods:ctor(goodsId, priceType)
    self:setName("UIBuyGoods");

    -- 初始化
    local node = cc.CSLoader:createNode("layout/market/BuyGoods.csb");
    self:addChild(node);
    self.node = node;

    if DungeonM.isInDungeon() then
        -- 迷宫中层级要调高
        self:setLocalZOrder(UIMgr.TOP_MENU_ZORDER + 11);
    end

    trace("UIBuyGoods", "goodsId = %d, priceType = %d", goodsId, priceType);

    self.goodsId = goodsId;
    self.priceType = priceType;

    if self:isDirectlyConfirm() then
        -- 如果配置了购买确认，直接弹购买确认即可
        self:setVisible(false);
        self:tryBuy();
    else
        self:setVisible(true);
    end

    -- 注册事件处理回调函数
    self:registerEventCallback()

    -- 注册各种点击事件
    self:registerTouchEvent();

    -- 重绘
    self:redraw();

    -- 适配
    self:resize();
end

-- 注册点击事件
function UIBuyGoods:registerTouchEvent()
    local node = self.node;

    -- 注册返回按钮点击事件
    local btnBack = findChildByName(node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 关闭当前界面
            AudioM.playFx("button_return");
            UIMgr.getCurrentScene():removeFormByName("UIBuyGoods");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));

    -- 注册购买按钮点击事件
    local btnBuy = findChildByName(node, "CT/btn_buy");
    local function onBuyClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_click");
            -- 尝试购买
            self:tryBuy();
        end
    end
    btnBuy:addTouchEventListener(onBuyClick);
    TextStyleM.setTextStyle(btnBuy, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBuy:setTitleText(getLocStr("btn_text_buy"));
end

-- 注册事件处理回调函数
function UIBuyGoods:registerEventCallback()
    self:registerScriptHandler(function(ev)
        if ev == "exit" then
            cclog("UIBuyGoods 界面析构清理");
            EventMgr.removeAll("UIBuyGoods");

            -- 显示商城主界面底部按钮
            local uiForm = UIMgr.getCurrentScene():getFormByName("UIMarketMain");
            if uiForm then
                uiForm:showButtons();
            end
        elseif ev == "enter" then
            if not self:isDirectlyConfirm() then
                -- 隐藏商城主界面底部按钮
                local uiForm = UIMgr.getCurrentScene():getFormByName("UIMarketMain");
                if uiForm then
                    uiForm:hideButtons();
                end
            end
        end
    end);
end

-- 是否直接显示购买确认
function UIBuyGoods:isDirectlyConfirm()
    -- 如果配置了购买确认，则直接显示
    local msg = MarketM.query(self.goodsId, "confirm");
    if type(msg) == "string" and msg ~= "" then
        return true;
    end
    return false;
end

-- 重绘
function UIBuyGoods:redraw()
    -- 获取商品信息
    local goodsInfo = MarketM.getGoodsInfo(self.goodsId);

    -- 显示商品名称
    local CT = findChildByName(self.node, "CT");
    local nameLabel = findChildByName(CT, "name");
    TextStyleM.setTextStyle(nameLabel, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_DARK_RED);
    nameLabel:setString(goodsInfo["name"]);

    -- 显示商品价格
    local attrib = table.keys(goodsInfo["price"])[1];
    local value  = table.values(goodsInfo["price"])[1];
    local priceIconImg  = findChildByName(CT, "price/icon");
    local priceLabel = findChildByName(CT, "price/value");

    if self.priceType == 1 then
        priceLabel:setString("×" .. tostring(value));

        if attrib == "gem" then
            priceIconImg:loadTexture(getSmallAttribIconPath("gem"));
        else
            local icon = FieldsM.query(attrib, "icon");
            priceIconImg:loadTexture(getSmallAttribIconPath(icon));
        end
        priceIconImg:setVisible(true);
        TextStyleM.setTextStyle(priceLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    else
        -- 真钱购买
        priceIconImg:setVisible(false);
        local sku = MarketM.querySku(self.goodsId);
        local price = "";
        if type(sku) ~= 'string' then
            price = string.format("$%.2f", table.values(goodsInfo["price"])[1]);
        else
            price = MarketM.getPriceBySku(sku);
        end
        priceLabel:setString("price");

        -- 设置货币文本的样式
        setCurrencyTextStyle(priceLabel);
    end

    -- 根据文本长度重新设置priceIcon的位置
    local textWidth = priceLabel:getContentSize().width;
    local iconWidth = priceIconImg:getContentSize().width;
    local textPosX  = priceLabel:getPositionX();
    priceIconImg:setPositionX(textPosX - textWidth - 25 - iconWidth / 2);

    -- 显示商品描述
    local descLabel = findChildByName(CT, "desc");
    local desc      = goodsInfo["desc"];

    if goodsInfo["bonus"] ~= nil and goodsInfo["bonus"][1] ~= nil and
       goodsInfo["bonus"][1][1] == 1 then
        desc = desc .. "\n\n" .. ItemM.getItemDesc(goodsInfo["bonus"][1][2]);
    end

    if string.match(desc, "{money}") ~= nil then
        -- 需要动态显示金币数量
        desc = string.gsub(desc, "{money}", tostring(FormulaM.invoke("CALC_GOODS_BONUS_MONEY", ME.user, goodsInfo["bonus_args"])));
    end

    if string.match(desc, "{debris}") ~= nil then
        -- 需要动态显示古遗迹碎片数量
        desc = string.gsub(desc, "{debris}", tostring(FormulaM.invoke("CALC_GOODS_BONUS_DEBRIS", ME.user, goodsInfo["bonus_args"])));
    end

    if string.match(desc, "{life}") ~= nil then
        -- 需要动态显示体力
        desc = string.gsub(desc, "{life}", tostring(ME.user.dbase:query("life", 0)));
        desc = string.gsub(desc, "{max_life}", tostring(ME.user:getMaxLife()));
    end

    local canBuyTimes = goodsInfo["one-off"] or 0;
    local alreadyBuyInfo = ME.user.dbase:query("market_buy", {});
    local alreadyBuyTimes;
    if string.match(desc, "{can_buy_times}") ~= nil then
        -- 显示总可购买次数
        desc = string.gsub(desc, "{can_buy_times}", tostring(canBuyTimes));
    end

    if string.match(desc, "{rest_buy_times}") ~= nil then
        -- 已购买次数
        if alreadyBuyInfo[self.goodsId] == nil then
            alreadyBuyTimes = 0;
        else
            alreadyBuyTimes = alreadyBuyInfo[self.goodsId]["buy_times"];
        end

         desc = string.gsub(desc, "{rest_buy_times}", tostring(canBuyTimes - alreadyBuyTimes));
    end

    TextStyleM.setTextStyle(descLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN, nil, nil, nil, nil, nil, TextStyleM.TEXT_SIZE_SMALL);
    applyString(descLabel, desc);
end

-- 适配
function UIBuyGoods:resize()
    local node = self.node;

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

-- 尝试购买
function UIBuyGoods:tryBuy()
    if MarketM.isRecharging() then
        trace("UIBuyGoods", "正在充值，请稍后。");
        closeFormByName("UIBuyGoods");
        return;
    end

    -- 获取商品信息
    local goodsInfo = MarketM.getGoodsInfo(self.goodsId);

    local function doBuy()
        -- 真钱购买
        if self.priceType ~= 1 then
            -- 如果在手机上，通过sdk购买（pt购买不限手机平台）
            if isAndroidPlatform() or isIosPlatform() or MarketM.isBuyGemByPt() then
                local goodsId = self.goodsId;
                closeFormByName("UIBuyGoods");

                if MarketM.isInlandPayWay() then
                    showInlandPayWay(goodsId);
                else
                    MarketM.buyByRmb(goodsId);
                end
            else
                -- 其他平台提示功能暂未开放
                alert(getLocStr("disable_function"));
                closeFormByName("UIBuyGoods");
            end
            return;
        end

        local ret = MarketM.canBuyGoods(self.goodsId)
        if true ~= ret or type(ret) == "string" then
            if "sold_out" == ret then
                -- 该商品已售完
                alert(string.format(getLocStr("market_goods_sold_out"), MarketM.query(self.goodsId, "name")));
            elseif "gem_lack" == ret then
                -- 钻石不足
                showGemLackConfirm();
            elseif type(ret) == "string" then
                -- 有提示语，提示之
                alert(getLocStr(ret));
            else
                -- 其他原因，统一提示失败
                trace("UIBuyGoods", "购买失败，原因：" .. tostring(ret))
                alert(getLocStr("market_buy_fail"));
            end

            -- 关闭界面
            closeFormByName("UIBuyGoods");
            return;
        end

        -- 购买
        Operation.cmd_buy_goods(self.goodsId);
    end

    local desc = goodsInfo["confirm"];
    if desc == nil or desc == "" then
        -- 无需确认，直接购买
        doBuy();
        return;
    end

    desc = MarketM.parseGoodsDesc(desc, goodsInfo);

    -- 获取确定按钮显示文本
    local okText;
    if goodsInfo["classify"] == "dlc" then
        -- 开启
        okText = getLocStr("btn_text_open");
    elseif goodsInfo["classify"] == "resource" then
        -- 购买
        okText = getLocStr("btn_text_buy");
    else
        -- 确定
        okText = getLocStr("btn_text_ok");
    end

    local function cancelFunc()
        closeFormByName("UIBuyGoods");
    end

    if goodsInfo["classify"] == "dlc" then
        local dbase = goodsInfo["dbase"] or {};
        local dungeonId = dbase["key_dungeon"];
        if type(dungeonId) == "number" and DungeonPuzzleM.isPuzzleDungeon(dungeonId) then

            if not DungeonPuzzleM.isHaveAllPuzzle(dungeonId) then
                desc = desc .. getLocStr("havent_get_all_puzzle");
            end

            confirm2(CONFIRM_TYPE_OK_CANCEL, goodsInfo["name"], desc,
                doBuy, cancelFunc, okText, getLocStr("btn_text_leave"), { ["backFunc"] = cancelFunc, });
        else
            confirm2(CONFIRM_TYPE_OK, goodsInfo["name"], desc,
                doBuy, nil, okText, nil, { ["backFunc"] = cancelFunc, });
        end
    else
        confirm2(CONFIRM_TYPE_OK, goodsInfo["name"], desc,
            doBuy, nil, okText, nil, { ["backFunc"] = cancelFunc, });
    end
end